import { Controller, Inject, Get, Post, Query, Body } from '@midwayjs/core'
import { DonateService } from '../../service/app/DonateService'
import { BaseController } from '../base.chontroller'

@Controller('/app/donate')
export class DonateController extends BaseController {
  @Inject()
  service!: DonateService

  // 获取需要捐赠的物资列表
  @Get('/list')
  async getDonateList(
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number
  ) {
    try {
      const data = await this.service.getDonateList(page || 1, pageSize || 10)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取物资列表失败')
    }
  }

  // 获取单个捐赠物资详情
  @Get('/detail')
  async getDonateDetail(@Query('id') id?: number) {
    if (!id) {
      return this.fail('缺少必要参数：id')
    }

    try {
      const data = await this.service.getDonateDetail(id)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取物资详情失败')
    }
  }

  // 添加捐赠记录
  @Post('/add-record')
  async addDonateRecord(@Body() data: {
    userId: number
    materialDonateId: number
    count: number
  }) {
    if (!data?.userId || !data?.materialDonateId || !data?.count) {
      return this.fail('缺少必要参数：userId、materialDonateId、count')
    }

    if (data.count <= 0) {
      return this.fail('捐赠数量必须大于0')
    }

    try {
      const result = await this.service.addDonateRecord(data)
      return this.success(result, '捐赠成功')
    } catch (err: any) {
      return this.fail(err.message || '添加捐赠记录失败')
    }
  }

  // 获取用户的捐赠记录
  @Get('/user-records')
  async getUserDonateRecords(
    @Query('userId') userId?: number,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number
  ) {
    if (!userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      const data = await this.service.getUserDonateRecords(userId, page || 1, pageSize || 10)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取用户捐赠记录失败')
    }
  }

  // 获取捐赠需求的捐赠记录列表
  @Get('/records')
  async getDonateRecords(
    @Query('materialDonateId') materialDonateId?: number,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number
  ) {
    if (!materialDonateId) {
      return this.fail('缺少必要参数：materialDonateId')
    }

    try {
      const data = await this.service.getDonateRecordsByDonateId(materialDonateId, page || 1, pageSize || 10)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取捐赠记录失败')
    }
  }
}
